package W072_081.src.controller;

import W072_081.src.dao.UserServiceInterface;
import W072_081.src.entity.User;
import W072_081.src.factory.ServiceFactory;
import W072_081.src.util.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/lc")
public class LoginCtrl extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        String user_json = JSONUtil.getJSON(request);
        User userToLogin = JSON.parseObject(user_json, User.class);
        JSONObject message = new JSONObject();
        try {
            ServiceFactory.getService(UserServiceInterface.class, "UserService").login(userToLogin);
            if (userToLogin.getId() == null) {
                message.put("msg", "用户名不存在或密码错误");
                message.put("code", "500");
                response.getWriter().println(JSON.toJSONString(message));
            } else {
                message.put("msg", "操作成功");
                message.put("code", "200");
                response.getWriter().println(JSON.toJSONString(message));
            }
        }catch (SQLException e){
            message.put("msg", "数据库操作异常");
            response.getWriter().println(JSON.toJSONString(message));
            e.printStackTrace();
        }catch (Exception e){
            message.put("msg", "网络异常");
            response.getWriter().println(JSON.toJSONString(message));
            e.printStackTrace();
        }
    }
}

